package com.cty.servlet;

import com.cty.service.UserService;
import com.cty.service.impl.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: cty
 * @Date: 2020/3/5 22:18
 * @Description:
 * @version: 1.0
 */
@WebServlet(name = "UserServlet", urlPatterns = "/user")
public class UserServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        // 获取spring容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        //spring和web整合后所有信息都存放在webApplicationContext
//        ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

        // 获取业务层对象
        userService = ac.getBean("userServiceImpl", UserServiceImpl.class);

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码格式
        req.setCharacterEncoding("utf-8");
        // 设置响应编码格式
        resp.setContentType("text/html;charset=utf-8");

        // 获取数据并存入request作用域
        req.setAttribute("userList", userService.showAll());

        // 请求转发
        req.getRequestDispatcher("/index.jsp").forward(req, resp);
    }
}
